package com.example.demo2Jdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/getbook")
public class GetBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");//用于解决服务器端向客户端传递数据的中文乱码问题
        PrintWriter out = resp.getWriter();//用于向客户端输出数据
        // 1.加载JDBC驱动程序
        try {
            Class.forName("com.mysql.jdbc.Driver");// 2．获得数据库连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore?serverTimezone=UTC", "root", "root");
            //3.执行sQL语句，实现增删改查操作
            String sql = "SELECT Bookid,Title,Author,Price FROM book";
            //①创建SQL语句
            PreparedStatement pstmt = conn.prepareStatement(sql);
            //②创建Preparedstatement对象
            ResultSet rs = pstmt.executeQuery(); //③执行查询，返回结果集l/4.结果处理。结果集rs有指针，初始指向数据行前面的空行
            out.print("<a href='addbook.html'>添加新书</a>");
            out.print("<table border=1><tr><td>编号</td><td>书名</td><td>作者</td><td>价格</td><td>修改</td><td>删除</td></tr>");
            while (rs.next()) { //rs.next()指针向下移一行，如果有数据返回true,否则返回false
                out.println("<tr><td>" + rs.getInt("Bookid")
                        + "</td><td>" + rs.getString("Title")
                        + "</td><td>" + rs.getString("Author")
                        + "</td><td>" + rs.getInt("Price")
                        + "</td><td>"
                        + "<a href='edit?id=" + rs.getInt("Bookid") + "'>修改</a>"
                        + "</td><td>"
                        + "<a href='delete?id=" + rs.getInt("Bookid") + "'>删除</a>"
                        + "</td>" + "</tr>");
            }
            out.print("</table>");
            rs.close();
                pstmt.close();
                conn.close(); //5.关闭连接
                out.flush();
                out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

